<template>
	<view class="home-container">
		<!-- 顶部搜索 -->
		<view class="custom-search-bar">
			<el-input v-model="searchValue" placeholder="搜索目的地/介绍/景点" clearable @keyup.enter="handleSearch">
				<template #prefix>
					<el-icon class="search-icon">
						<search />
					</el-icon>
				</template>
			</el-input>
		</view>

		<!-- 信息列表容器 -->
		<scroll-view class="scroll-container" scroll-y :enable-flex="true" :scroll-top="scrollTop"
			@scrolltolower="loadMore" @scroll="handleScroll">
			<view class="columns-wrapper">
				<!-- 左栏 -->
				<view class="left-column">
					<travel-card v-for="(item, index) in leftColumnItems" :key="'left-'+index" v-bind="item"
						@click="navigateToDetail(item)" />
				</view>

				<!-- 右栏 -->
				<view class="right-column">
					<travel-card v-for="(item, index) in rightColumnItems" :key="'right-'+index" v-bind="item"
						@click="navigateToDetail(item)" />
				</view>
			</view>

		</scroll-view>
		<!-- 回到顶部按钮 -->
		<view class="back-to-top" @click="scrollToTop" v-show="showBackToTop">
			<text>↑</text>
		</view>

	</view>
</template>

<script>
	import {
		ElInput,
		ElIcon
	} from 'element-plus'
	import {
		Search
	} from '@element-plus/icons-vue'
	import TravelCard from './comment/travelCard.vue';
	import {
		getParams
	} from '@/axios/http';
	import {
		ElMessage
	} from 'element-plus';
	export default {
		components: {
			ElInput,
			ElIcon,
			Search,
			'travel-card': TravelCard
		},
		data() {
			return {
				searchText: '',
				searchValue: '',
				attractions: [],
				pageSize: 10, // 每页加载数量
				currentPage: 1, // 当前页码
				loading: false, // 加载状态
				noMoreData: false, // 是否没有更多数据
				scrollTop: 0, // 滚动位置
				showBackToTop: true, // 控制显示/隐藏返回顶部按钮
				lastId: 1,
				isNavigating: false, // 添加跳转锁
			}
		},
		computed: {
			// 计算当前显示的数据
			displayedItems() {
				return this.attractions.slice(0, this.pageSize * this.currentPage);
			},

			//将数据分栏
			leftColumnItems() {
				// 取奇数索引项作为左栏
				return this.attractions.filter((item, index) => index % 2 === 0);
			},
			rightColumnItems() {
				// 取偶数索引项作为右栏
				return this.attractions.filter((item, index) => index % 2 === 1);
			}
		},

		async onLoad() {
			// 获取 Cookie
			const cookieValue = uni.getStorageSync('LoginUser');
			// console.log("Index onShow  cookieValue:", cookieValue)

			if (!cookieValue) {
				console.error("未登录！")
			}
			// console.log("this.lastId" + this.lastId)
			//初始化加载
			await this.loadData();

		},
		methods: {

			//注销清空cookie
			logout() {
				uni.removeStorageSync('LoginUser');
			},
			//回到顶部
			handleScroll(e) {
				// 当滚动高度超过 500 时显示返回顶部按钮
				this.showBackToTop = e.detail.scrollTop > 500;
				this.scrollTop = e.detail.scrollTop;
			},
			// 返回顶部
			scrollToTop() {
				this.scrollTop = 0;
				this.showBackToTop = false;
				// 如果需要动画效果，可以使用 uni.pageScrollTo
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},
			// 搜索功能
			handleSearch(e) {
				console.log('搜索:', this.searchValue);
				// 重置状态并重新加载
				this.attractions = [];
				this.currentPage = 1;
				this.lastId = 1;
				this.noMoreData = false;
				this.loadData();
			},
			navigateToDetail(item) {

				// console.log("父组件点击item", item) 
				if (this.isNavigating) return;
				this.isNavigating = true;
				uni.navigateTo({
					url: `/pages/attractionInfo/attractionInfo?id=${item.attractionId} `,
					complete: () => {//跳转锁
						this.isNavigating = false;
					}
				});
			},
			// 加载更多数据
			loadMore() {
				// console.log("下拉到底了", this.scrollTop)
				console.log("当前页码", this.currentPage)
				this.loadData();

			},
			//请求数据一次请求10条
			async loadData() {

				if (this.loading || this.noMoreData) {
					ElMessage({
						message: '没有更多数据了',
						type: 'warning',
						offset: 250,
					})
					return
				};
				this.loading = true;



				try {
					let data = {
						keyword: this.searchValue,
						lastId: this.lastId,
						limit: this.pageSize
					}
					// console.log("请求分页传递的data:", data)

					let getUrl = data.keyword === '' ? '/attractions' : '/search';
					// console.log("getUrl", getUrl)
					const response = await getParams(getUrl, data); // 调用封装的 GET 请求 请求所有的景点信息


					// console.log("请求到的response:", response.data)
					if (response.data.count === 0) {
						this.noMoreData = true;
						ElMessage({
							message: '没有更多数据了',
							type: 'warning',
							offset: 250,
						})
						return;
					}

					this.attractions == [] ? this.attractions = response.data.attractions : this.attractions = [...this.attractions, ...response.data.attractions];
					// console.log("请求后的attractions", this.attractions)
					this.currentPage++;
					this.lastId = this.attractions[this.attractions.length - 1].attractionId + 1;
					// console.log("请求后的this.lastId", this.lastId)
				} catch (error) {
					console.error('加载数据失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			}



		}
	}
</script>

<style>
	.back-to-top {
		position: fixed;
		right: 30rpx;
		bottom: 150rpx;
		width: 80rpx;
		height: 80rpx;
		background-color: #007AFF;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		color: white;
		font-size: 36rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
		z-index: 999;
		opacity: 0.8;
		transition: opacity 0.3s;
	}

	.back-to-top:active {
		opacity: 1;
		background-color: #0062CC;
	}

	.custom-search-bar {
		padding: 15px;
		background-color: #f5f5f5;
	}

	.custom-search-bar .el-input {
		--el-input-height: 38px;
		--el-input-border-radius: 19px;
		--el-input-bg-color: #ffffff;
	}

	.custom-search-bar .el-input__wrapper {
		padding-left: 15px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
	}

	.custom-search-bar .search-icon {
		color: #999;
		margin-right: 8px;
	}

	.columns-wrapper {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	.home-container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;

		.search-bar {
			margin-bottom: 20rpx;
			background-color: #fff;
			padding: 20rpx;
			border-radius: 50rpx;
		}

		.scroll-container {
			height: calc(100vh - 120rpx);
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
		}



		.left-column,
		.right-column {
			width: 48%;
			height: calc(100vh - 180rpx);
		}

		.load-more {
			width: 100%;
			text-align: center;
			padding: 20rpx;
			color: #999;
			font-size: 24rpx;
		}
	}

	.uni-scroll-view-content {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}
</style>